package cn.felord.debezium.service;

import cn.felord.debezium.dao.DetectionRlMapper;
import cn.felord.debezium.dao.ScaleAlarmMasterMapper;
import cn.felord.debezium.dao.ScaleEquipmentMamageMapper;
import cn.felord.debezium.dao.SmelterMelterStandardMapper;
import cn.felord.debezium.entity.DetectionRl;
import cn.felord.debezium.entity.ScaleEquipmentMamage;
import cn.felord.debezium.entity.SmelterMelterStandard;
import cn.felord.debezium.utils.AuToSend;
import cn.felord.debezium.utils.CRC16Checksum;
import cn.felord.debezium.utils.DateUtil;
import cn.felord.debezium.utils.String2AcsII16;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@Slf4j
@Service
public class DetectService {
    @Autowired
    DetectionRlMapper detectionRlMapper;
    @Autowired
    SmelterMelterStandardMapper smelterMelterStandardMapper;
    @Autowired
    ScaleEquipmentMamageMapper scaleEquipmentMamageMapper;
    @Autowired
    ScaleAlarmMasterMapper scaleAlarmMasterMapper;
    @Autowired
    AuToSend auToSend;

    /**
     * 发给合金辅料仪
     * @throws IOException
     */
    public void push_detection(String id) throws IOException {
        DetectionRl detectionRl = new DetectionRl();
        detectionRl.setId(Long.valueOf(id));
        DetectionRl detectionRl1 = detectionRlMapper.selectDetectionRlById(Long.valueOf(id));//质检
        if(detectionRl1 == null){
            log.info("质检信息不存在");
            return ;
        }
        String plant = detectionRl.getPlant();
        if(plant == null){
            log.error("车间信息异常");
            return;
        }
        String factoryCode = plant.split("-")[1];
        SmelterMelterStandard smelterMelterStandard1 = new SmelterMelterStandard();
        smelterMelterStandard1.setFactoryCode(factoryCode);
        List<SmelterMelterStandard> smelterMelterStandards = smelterMelterStandardMapper.selectByPrimaryList(smelterMelterStandard1);
        HashMap<String,SmelterMelterStandard> dist = new HashMap<>();//标准
        for (SmelterMelterStandard smelterMelterStandard : smelterMelterStandards) {
            System.out.println("标准" + smelterMelterStandard.getSmelterNum() + smelterMelterStandard.getcMax());
            dist.put(smelterMelterStandard.getSmelterNum(),smelterMelterStandard);
        }
        System.out.println("检验开始===" + DateUtil.sdf.format(System.currentTimeMillis()/1000));
        String send = checkQual(detectionRl1, dist);
        if(send.length() == 0){
            log.info("不用发送，都合格！");
            return ;
        }
        String lh = detectionRl1.getFurnaceNum();
        String lch =  detectionRl.getMeltNum();  //抬头添加炉号 和次号
        String lh16 = "0000000000000000";//占位16个0
        String lch16 = "000000000000000000000000";
        if(!StringUtils.isEmpty(lh)){
            lh16 = String2AcsII16.string2hex(lh,16);
        }
        if(!StringUtils.isEmpty(lch)){
            lch16 = String2AcsII16.string2hex(lch,24);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        String[] kg = format.split(" ");
        String[] kg_ = kg[0].split("-");
        String[] kgm = kg[1].split(":");
        String year = kg_[0];
        String mo = kg_[1];
        String day = kg_[2];
        String HH = kgm[0];
        String MM = kgm[1];
        String ss = kgm[2];
        String year16 = String2AcsII16.int10to16_4(Integer.valueOf(year));
        String mo_day16 = String2AcsII16.int10to16_2(Integer.valueOf(mo)) + String2AcsII16.int10to16_2(Integer.valueOf(day));
        String HH_MM16 = String2AcsII16.int10to16_2(Integer.valueOf(HH)) + String2AcsII16.int10to16_2(Integer.valueOf(MM));
        String ss16 = String2AcsII16.int10to16_2(Integer.valueOf(ss)) + "00";
        String tsl16 = "0000";
        String yuliu1 = "000000000000";
        String yuliu2 = "00000000";
        ScaleEquipmentMamage scaleEquipmentMamage = scaleEquipmentMamageMapper.selectScaleEquipmentMamageByFurnanceNum(lh);
        if(scaleEquipmentMamage == null){
            log.error( lh + "不存在绑定设备，请维护信息！");
            return ;
        }
        String type = scaleEquipmentMamage.getType();//KDTC
        String KDTC16 = String2AcsII16.string2hex("KDTC");
        String equNum = scaleEquipmentMamage.getEquNum();//00000001
        if(equNum.length() != 8){
            log.error("设备编码不是8位，预警！！！请维护正确设备信息");
            return ;
        }
        String content = KDTC16 + equNum + lh16 + lch16 +  tsl16 + year16 + mo_day16 + HH_MM16
                + ss16 + yuliu1 + send + yuliu2 ;
        int length = content.length();
        int jcq = length / 4;// 不合格元素个数 * 4，再上位机收到光谱数转16进制
        int zjs = jcq * 2;//寄存器数目*2再转16进制
        StringBuffer sf = new StringBuffer();
        sf.append("FE01100000");
        sf.append(String2AcsII16.int10to16_4(jcq) +  String2AcsII16.int10to16_4(zjs));
        sf.append(content);
        String crc_str = "01100000" + String2AcsII16.int10to16_4(jcq) +  String2AcsII16.int10to16_4(zjs) + content;
        String CRC_CHECK_CODE = CRC16Checksum.getCrc16ModBus(crc_str);//检验码
        sf.append(CRC_CHECK_CODE);
        sf.append("FF");
        log.info("发送不合格：" + sf.toString());
        auToSend.sendEquip(sf.toString(),type + equNum);
//        ScaleAlarmMaster scaleAlarmMaster = new ScaleAlarmMaster();
//        scaleAlarmMaster.setLh(lh);
//        scaleAlarmMaster.setLch(lch);
//        scaleAlarmMaster.setEquNum("KDTC" + equNum);
//        scaleAlarmMaster.setRetain1(sjz + "");//铁水重
//        scaleAlarmMaster.setCreateTime(new Date());
//        scaleAlarmMaster.setCreateUser("tcpServer");
//        scaleAlarmMasterMapper.insertScaleAlarmMaster(scaleAlarmMaster);
    }
    public String checkQual(DetectionRl item, HashMap<String, SmelterMelterStandard> dist){
        SmelterMelterStandard standard =  dist.get(item.getMarkId());
        if(standard == null){
            log.error("无标准，不发送");
            return "";
        }
        StringBuffer send = new StringBuffer();
        log.info("走标准" +  item.getMarkId());
        Double C = new BigDecimal(item.getC().toString()).setScale(3,BigDecimal.ROUND_UP).doubleValue();
        if(C < new BigDecimal(standard.getcMin()).doubleValue()){
            System.out.println("C不合格" + C);
            System.out.println("C不合格min" + standard.getcMin());
            System.out.println("C不合格max" + standard.getcMax());
            send.append(String2AcsII16.string2Char2asciiValueint10to16("C"));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(C*1000).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getcMin()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getcMax()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
        }
        Double Si = new BigDecimal(item.getSi().toString()).setScale(3,BigDecimal.ROUND_UP).doubleValue();
        if(Si < new BigDecimal(standard.getSiMin()).doubleValue()){
            System.out.println("Si不合格" + Si);
            System.out.println("Si不合格min" + standard.getSiMin());
            System.out.println("Si不合格max" + standard.getSiMax());
            send.append(String2AcsII16.string2Char2asciiValueint10to16_2("S"));
            send.append(String2AcsII16.string2Char2asciiValueint10to16_2("i"));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(Si*1000).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getSiMin()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getSiMax()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
        }
        Double Mn = new BigDecimal(item.getMn().toString()).setScale(3,BigDecimal.ROUND_UP).doubleValue();
        if(Mn < new BigDecimal(standard.getMnMin()).doubleValue()){
            System.out.println("Mn不合格" + Mn);
            System.out.println("不合格min" + standard.getMnMin());
            System.out.println("不合格max" + standard.getMnMax());
            send.append(String2AcsII16.string2Char2asciiValueint10to16_2("M"));
            send.append(String2AcsII16.string2Char2asciiValueint10to16_2("n"));
            send.append(String2AcsII16.int10to16_4(new BigDecimal( Mn*1000).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getMnMin()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getMnMax()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
        }
        Double P = new BigDecimal(item.getP().toString()).setScale(3,BigDecimal.ROUND_UP).doubleValue();
        if(P < new BigDecimal(standard.getpMin()).doubleValue()){
            System.out.println("P不合格" + P);
            System.out.println("不合格min" + standard.getpMin());
            System.out.println("不合格max" + standard.getpMax());
            send.append(String2AcsII16.string2Char2asciiValueint10to16("P"));
            send.append(String2AcsII16.int10to16_4(new BigDecimal( P*1000).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getpMin()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getpMax()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
        }
        Double S = new BigDecimal(item.getS().toString()).setScale(3,BigDecimal.ROUND_UP).doubleValue();
        if(S < new BigDecimal(standard.getsMin()).doubleValue()){
            System.out.println("S不合格" + S);
            System.out.println("不合格min" + standard.getsMin());
            System.out.println("不合格max" + standard.getsMax());
            send.append(String2AcsII16.string2Char2asciiValueint10to16("S"));
            send.append(String2AcsII16.int10to16_4(new BigDecimal( S*1000).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getsMin()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getsMax()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
        }
        if(item.getTi()!=null && !StringUtils.isEmpty(item.getTi().toString())){
            Double Ti = new BigDecimal(item.getTi().toString()).setScale(3,BigDecimal.ROUND_UP).doubleValue();
            if(Ti < new BigDecimal(standard.getTiMin()).doubleValue()){
                System.out.println("Ti不合格" + Ti);
                System.out.println("不合格min" + standard.getTiMin());
                System.out.println("不合格max" + standard.getTiMax());
                send.append(String2AcsII16.string2Char2asciiValueint10to16_2("T"));
                send.append(String2AcsII16.string2Char2asciiValueint10to16_2("i"));
                send.append(String2AcsII16.int10to16_4(new BigDecimal( Ti*1000).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
                send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getTiMin()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
                send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getTiMax()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            }
        }
        if(item.getCr() != null && item.getCr().toString().trim() != ""){
            Double Cr = new BigDecimal(item.getCr().toString()).setScale(3,BigDecimal.ROUND_UP).doubleValue();
            if(Cr < new BigDecimal(standard.getCrMin()).doubleValue()){
                System.out.println("Cr不合格" + Cr);
                System.out.println("不合格min" + standard.getCrMin());
                System.out.println("不合格max" + standard.getCrMax());
                send.append(String2AcsII16.string2Char2asciiValueint10to16_2("C"));
                send.append(String2AcsII16.string2Char2asciiValueint10to16_2("r"));
                send.append(String2AcsII16.int10to16_4(new BigDecimal( Cr*1000).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
                send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getCrMin()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
                send.append(String2AcsII16.int10to16_4(new BigDecimal(standard.getCrMax()).multiply(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue()));
            }
        }
        return send.toString();
    }

}
